package com.dianrui.operation.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.ChangeBatteryListAdapter;
import com.dianrui.operation.adapter.SecretProtocolAdapter;
import com.dianrui.operation.bean.BikePointModel;
import com.dianrui.operation.bean.Charge;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.ActionItem;
import com.dianrui.operation.util.MyOrientationListener;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.TitlePopup;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.Packet;
import com.tbit.tbitblesdk.protocol.callback.PacketCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;
import com.xiaoantech.sdk.XiaoanBleApiClient;
import com.xiaoantech.sdk.ble.model.Response;
import com.xiaoantech.sdk.listeners.BleCallback;
import com.xiaoantech.sdk.listeners.BleStateChangeListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ChangeBatteryActivity extends BaseActivity implements AMapLocationListener {
    private String mTitles;
    public String CUSTOMMARKER = "Markers";
    private LatLng latLng;
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;
    private MyOrientationListener myOrientationListener;
    private boolean isFirstLoc = true;
    private AMap aMap;
    private Marker clickMaker;
    private double currentLatitude;
    private double currentLongitude;
    private List<BikePointModel> bikePointList = new ArrayList<>();
    private List<Marker> mAllCollegeMarker = new ArrayList<>();
    private List<Charge> chargetList = new ArrayList<>();
    private List<LatLng> mAreaPoints = new ArrayList<>();
    private BluetoothAdapter mBlueadapter;
    private ChangeBatteryListAdapter changeBatteryListAdapter;
    private List<Charge> emptyChargetList = new ArrayList<>();
    private BitmapDescriptor bitD_NoStop;
    private BitmapDescriptor bitD_fiftyCarEle;
    private BitmapDescriptor bitD_fortyCarEle;
    private BitmapDescriptor bitD_thiryCarEle;
    private BitmapDescriptor bitD_twentCarEle;
    private TitlePopup titlePopup;
    private XiaoanBleApiClient apiClient;
    private XiaoanBleApiClient.Builder builder;

    @BindView(R.id.top_right_imgs)
    ImageView topRightImg;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.mapviews)
    MapView mapviews;
    @BindView(R.id.track_pullup)
    ImageView trackPullup;
    @BindView(R.id.track_pulldown)
    ImageView trackPulldown;

    @BindView(R.id.fifty_layout)
    LinearLayout fiftyLayout;
    @BindView(R.id.fifty_number)
    TextView fiftyNumber;

    @BindView(R.id.forty_layout)
    LinearLayout fortyLayout;
    @BindView(R.id.forty_number)
    TextView fortyNumber;

    @BindView(R.id.thirty_number)
    TextView thirtyNumber;
    @BindView(R.id.thirty_layout)
    LinearLayout thirtyLayout;
    @BindView(R.id.twenty_number)
    TextView twentyNumber;
    @BindView(R.id.twenty_layout)
    LinearLayout twentyLayout;

    @BindView(R.id.mCoordinatorLayout)
    CoordinatorLayout mCoordinatorLayout;
    @BindView(R.id.mAppBarLayout)
    AppBarLayout mAppBarLayout;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapviews.onSaveInstanceState(outState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.battery_change;
    }

    @Override
    public void initView() {
        TbitBle.initialize(ChangeBatteryActivity.this, new SecretProtocolAdapter());//泰比特蓝牙初始化
        mBlueadapter = BluetoothAdapter.getDefaultAdapter();
        topRightImg.setImageResource(R.mipmap.changbattery_qr_code);
        topRightImg.setVisibility(View.VISIBLE);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("title");
            }
        }
        builder = new XiaoanBleApiClient.Builder(this);
        apiClient = builder.build();
        title.setText(getString(R.string.shortage_car_battary_txt));
        aMap = mapviews.getMap();
        loadLocation();
        tagClick=0;
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        aMap.setOnMarkerClickListener(markerClickListener);
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        aMap.setOnInfoWindowClickListener(listener);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMaker != null && clickMaker.isInfoWindowShown()) {
                    clickMaker.hideInfoWindow();
                }
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        changeBatteryListAdapter = new ChangeBatteryListAdapter(R.layout.item_changebattery_list, chargetList);
        recyclerView.setAdapter(changeBatteryListAdapter);

        changeBatteryListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Charge charge = (Charge) adapter.getData().get(position);
                int v = view.getId();
                switch (v) {
                    case R.id.startdefense_btn://启动
                        sendCommand(charge.number, "1", "2", "1");
                        break;
                    case R.id.withdrawdevice_btn://关闭
                        sendCommand(charge.number, "0", "2", "2");
                        break;
                    case R.id.oppacc_btn://开仓
                        sendCommand(charge.number, "0", "5", "3");
                        break;
                    case R.id.play_btn://播报
                        sendCommand(charge.number, "0", "1", "4");
                        break;
                    case R.id.gps_btn://gps重启
                        sendCommand(charge.number, "0", "9", "");
                        break;

                    case R.id.check_map://查看地图
                        try {
                            CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams()).getBehavior();
                            if (behavior instanceof BottomSheetBehavior) {
                                BottomSheetBehavior myBehavior = (BottomSheetBehavior) behavior;
                                myBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(charge.glat, charge.glng), 17f));

                        break;


                    case R.id.finish_btn://完成
                        batteryFinish(charge.number);
                        try {
                            CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams()).getBehavior();
                            if (behavior instanceof BottomSheetBehavior) {
                                BottomSheetBehavior myBehavior = (BottomSheetBehavior) behavior;
                                myBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;

                    default:
                        break;
                }
            }
        });

        loadMarker();
        loadTitlePop();
        loadCoordinatorListener();
    }

    //初始化右上角的popwindow
    private void loadTitlePop() {
        String[] texts = {"扫一扫", "输入编码"};
        List<ActionItem> list = new ArrayList<>();
        ActionItem bean = null;
        for (int i = 0; i < texts.length; i++) {
            bean = new ActionItem();
            bean.setText(texts[i]);
            list.add(bean);
        }
        titlePopup = new TitlePopup(this, list);
        titlePopup.setOnItemClick(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        titlePopup.dismiss();
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (ContextCompat.checkSelfPermission(ChangeBatteryActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                                Intent intent = new Intent(ChangeBatteryActivity.this, OpeationCaptureActivity.class);
                                intent.putExtra("camflag", "8");
                                startActivityForResult(intent, 108);
                            } else {
                                ActivityCompat.requestPermissions(ChangeBatteryActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                            }
                        } else {
                            Intent intent = new Intent(ChangeBatteryActivity.this, OpeationCaptureActivity.class);
                            intent.putExtra("camflag", "8");
                            startActivityForResult(intent, 108);
                        }
                        break;
                    case 1:
                        titlePopup.dismiss();
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(ChangeBatteryActivity.this, R.style.RcDialog);
                        View view2 = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.dialog_code, null);
                        final AlertDialog dialog1 = builder1.create();
                        dialog1.setView(view2);
                        final TextView yes_dialog = view2.findViewById(R.id.yes_dialog_ask);
                        final TextView no_dialog = view2.findViewById(R.id.no_dialog_ask);
                        final EditText codeEdit = view2.findViewById(R.id.code_edit);

                        yes_dialog.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (StringUtils.isEmpty(codeEdit.getText().toString())) {
                                    ToastUtil.showToast(getString(R.string.code_txt_title));
                                } else {
                                    dialog1.dismiss();
                                    getCarinfo(codeEdit.getText().toString());
                                }

                            }
                        });
                        no_dialog.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog1.dismiss();

                            }
                        });
                        dialog1.show();
                        break;

                    default:
                        break;
                }
            }
        });


    }

    @SuppressLint("InflateParams")
    private void loadMarker() {
        View fiftyView = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.fifty_down, null);

        bitD_fiftyCarEle = BitmapDescriptorFactory.fromView(fiftyView);

        View fortyView = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.forty_down, null);

        bitD_fortyCarEle = BitmapDescriptorFactory.fromView(fortyView);

        View thirydownView = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.thiry_down, null);

        bitD_thiryCarEle = BitmapDescriptorFactory.fromView(thirydownView);

        View twentdownView = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.twent_down, null);

        bitD_twentCarEle = BitmapDescriptorFactory.fromView(twentdownView);

        View view1 = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.over_nostop_point, null);
        bitD_NoStop = BitmapDescriptorFactory.fromView(view1);

    }

    //监听Coordinator滑动
    private void loadCoordinatorListener() {
        try {
            CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams()).getBehavior();
            if (behavior instanceof BottomSheetBehavior) {
                BottomSheetBehavior myBehavior = (BottomSheetBehavior) behavior;
                myBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                    @Override
                    public void onStateChanged(@NonNull View bottomSheet, int newState) {
                        if (newState == 3) {//手拉到顶部值的是3
                            trackPulldown.setVisibility(View.VISIBLE);
                            trackPullup.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                        if (slideOffset == 0.0f) {//手拉到底部是0.0
                            trackPulldown.setVisibility(View.GONE);
                            trackPullup.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(ChangeBatteryActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(ChangeBatteryActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
        bitD_fiftyCarEle.recycle();
        bitD_fortyCarEle.recycle();
        bitD_thiryCarEle.recycle();
        bitD_twentCarEle.recycle();
        bitD_NoStop.recycle();
        TbitBle.destroy();
        TbitBle.disConnect();
        if (apiClient != null) {
            apiClient.disConnect();
            apiClient.onDestroy();
        }
        if (mAllCollegeMarker != null) {
            mAllCollegeMarker.clear();
            mAllCollegeMarker=null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }

    private int tagClick;

    @OnClick({R.id.back, R.id.bigger, R.id.top_right_imgs, R.id.smaller, R.id.refresh, R.id.location, R.id.fifty_layout, R.id.forty_layout, R.id.thirty_layout, R.id.twenty_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.top_right_imgs:
                titlePopup.showPopupWindow(view);
                break;

            case R.id.refresh:
                if (currentLatitude == 0.0000 && currentLongitude == 0.0000) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(ChangeBatteryActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                                aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(currentLatitude, currentLongitude)));
                            }
                        }, 500);
                    } else {
                        ActivityCompat.requestPermissions(ChangeBatteryActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 3);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                            aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(currentLatitude, currentLongitude)));
                        }
                    }, 500);
                }
                break;

            case R.id.location:
                if (currentLatitude == 0.0000 && currentLongitude == 0.0000) {
                    return;
                }
                 currentStatusRfresh();
                break;

            case R.id.bigger:
                MyUtil.setMapStatus(mapviews, MyUtil.getZoom(mapviews) - 1);
                break;
            case R.id.smaller:
                MyUtil.setMapStatus(mapviews, MyUtil.getZoom(mapviews) + 1);
                break;

            case R.id.fifty_layout:
                tagClick = 0;
                clearMarkers();

                fiftyLayout.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));
                fortyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                thirtyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                twentyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                name.setText(getString(R.string.fifty_percent));

                showMarkers(50);
                changeBatteryListAdapter.setNewData(emptyChargetList);

                break;

            case R.id.forty_layout:
                tagClick = 1;
                clearMarkers();
                fiftyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                fortyLayout.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));
                thirtyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                twentyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                name.setText(getString(R.string.forty_percent));
                showMarkers(40);
                changeBatteryListAdapter.setNewData(emptyChargetList);
                break;

            case R.id.thirty_layout:
                tagClick = 2;
                clearMarkers();
                fiftyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                fortyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                thirtyLayout.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));
                twentyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                name.setText(getString(R.string.thiry_percent));

                showMarkers(30);
                changeBatteryListAdapter.setNewData(emptyChargetList);
                break;

            case R.id.twenty_layout:
                tagClick = 3;
                clearMarkers();
                fiftyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                fortyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                thirtyLayout.setBackgroundColor(getResources().getColor(R.color.white));
                twentyLayout.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));
                name.setText(getString(R.string.twent_percent));

                showMarkers(20);
                changeBatteryListAdapter.setNewData(emptyChargetList);
                break;

            default:
                break;
        }
    }

    private void currentStatusRfresh() {
        if (tagClick == 0) {
            clearMarkers();
            showMarkers(50);
            changeBatteryListAdapter.setNewData(emptyChargetList);
        }else if (tagClick == 1) {
            clearMarkers();
            showMarkers(40);
            changeBatteryListAdapter.setNewData(emptyChargetList);
        }else if (tagClick == 2) {
            clearMarkers();
            showMarkers(30);
            changeBatteryListAdapter.setNewData(emptyChargetList);
        }else if (tagClick == 3) {
            clearMarkers();
            showMarkers(20);
            changeBatteryListAdapter.setNewData(emptyChargetList);
        }
    }

    private void showMarkers(int limit) {
        emptyChargetList.clear();

        for (int i = 0; i < chargetList.size(); i++) {

            if (chargetList.get(i).battery <= 20) {
                emptyChargetList.add(chargetList.get(i));
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(chargetList.get(i).glat, chargetList.get(i).glng)).icon(bitD_twentCarEle).zIndex(99);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCollegeMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(chargetList.get(i));
            }

            if (limit > 20 && (chargetList.get(i).battery > 20 && chargetList.get(i).battery <= 30)) {
                emptyChargetList.add(chargetList.get(i));
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(chargetList.get(i).glat, chargetList.get(i).glng)).icon(bitD_thiryCarEle).zIndex(99);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCollegeMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(chargetList.get(i));
            }

            if (limit > 30 && (chargetList.get(i).battery > 30 && chargetList.get(i).battery <= 40)) {
                emptyChargetList.add(chargetList.get(i));
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(chargetList.get(i).glat, chargetList.get(i).glng)).icon(bitD_fortyCarEle).zIndex(99);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCollegeMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setObject(chargetList.get(i));
            }
            if (limit > 40 && (chargetList.get(i).battery > 40 && chargetList.get(i).battery <= 50)) {
                emptyChargetList.add(chargetList.get(i));
                MarkerOptions markerOptions1 = new MarkerOptions();
                markerOptions1.position(new LatLng(chargetList.get(i).glat, chargetList.get(i).glng)).icon(bitD_fiftyCarEle).zIndex(99);
                Marker marker = aMap.addMarker(markerOptions1);
                mAllCollegeMarker.add(marker);
                marker.setTitle(CUSTOMMARKER);
                marker.setSnippet(CUSTOMMARKER);
                marker.setObject(chargetList.get(i));
            }

        }
    }

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    //显示站点
    private void getStation(LatLng latLng) {
        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("type_id", "2");
        networksJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        networksJsonobject.addProperty("radius", "0");//周边范围：默认1公里或者0.5公里
        StringBuilder stationBuilder=new StringBuilder();
        stationBuilder.append(SharedUtil.getUrl()).append(Url.GETNETWORK_BIKE);
        XHttpRequest.getInstance().postRequests(stationBuilder.toString(), networksJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (bikePointList != null) {
                                bikePointList.clear();
                            }
                            if (mAreaPoints != null) {
                                mAreaPoints.clear();
                            }
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if(jsonObject.optString("data").equals("{}")){
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                                } else if (jsonObject.optString("data").equals("[]")) {
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                                } else {
                                    JSONArray gfixedPath = jsonObject.optJSONObject("area").optJSONArray("gfixed_path");
                                    if (gfixedPath.length() > 0) {
                                        for (int j = 0; j < gfixedPath.length(); j++) {
                                            JSONObject jsonObject3 = gfixedPath.optJSONObject(j);
                                            mAreaPoints.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                                        }
                                        if (mAreaPoints.size() > 0) {
                                            PolygonOptions polygonOptions = new PolygonOptions();
                                            polygonOptions.addAll(mAreaPoints);
                                            polygonOptions.strokeWidth(4);
                                            polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                                            polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                                            aMap.addPolygon(polygonOptions);
                                        }
                                        LatLngBounds.Builder b = LatLngBounds.builder();

                                        for (LatLng latLng : mAreaPoints) {//这个api表示区域或者多边形显示手机屏幕中央
                                            b.include(latLng);
                                        }
                                        LatLngBounds bounds = b.build();
                                        aMap.moveCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 130, 130, 580, 260));
                                    }

                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        BikePointModel bikeModel = new BikePointModel();
                                        bikeModel.blat = jsonArray.optJSONObject(i).optDouble("glat");
                                        bikeModel.blng = jsonArray.optJSONObject(i).optDouble("glng");
                                        bikeModel.vehicle_number = jsonArray.optJSONObject(i).optString("vehicle_number");
                                        bikePointList.add(bikeModel);

                                        if ("1".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            List<LatLng> points = new ArrayList<>();
                                            if (points != null) {
                                                points.clear();
                                            }
                                            JSONArray jsonArray3 = jsonArray.optJSONObject(i).optJSONArray("fixed_path");
                                            if (jsonArray3.length() > 0) {
                                                for (int j = 0; j <= jsonArray3.length(); j++) {
                                                    if (j == jsonArray3.length()) {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    } else {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(j);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    }

                                                }

                                                if (points.size() < 2) {
                                                    return;
                                                }

                                                if (jsonArray.optJSONObject(i).optString("is_forbid").equals("1")) {
                                                    aMap.addPolyline((new PolylineOptions()).addAll(points).width(4).setDottedLine(true).color(Color.RED));
                                                    MarkerOptions markerOptions1 = new MarkerOptions();
                                                    markerOptions1.position(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng)).icon(bitD_NoStop);
                                                    Marker marker = aMap.addMarker(markerOptions1);
                                                } else {
                                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                                    List<Integer> textureIndexs = new ArrayList<>();
                                                    textureIndexs.add(i);
                                                    List<LatLng> overLatlngList = new ArrayList<>(points);

                                                    PolylineOptions polylineOptions = new PolylineOptions();
                                                    polylineOptions.addAll(overLatlngList);
                                                    polylineOptions.width(4);
                                                    polylineOptions.setCustomTextureList(textureList);
                                                    polylineOptions.setCustomTextureIndex(textureIndexs);
                                                    polylineOptions.setDottedLine(true);
                                                    polylineOptions.setUseTexture(true);
                                                    aMap.addPolyline(polylineOptions);
                                                }
                                            }

                                        } else if ("0".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            int networkRange = jsonArray.optJSONObject(i).optInt("network_range");
                                            aMap.addCircle(new CircleOptions()
                                                    .center(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng))
                                                    .radius(networkRange)
                                                    .fillColor(Color.argb(46,64,194,134)).strokeWidth(4).strokeColor(Color.argb(46,64,194,134)));
                                        }
                                    }
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                spUtils.clear();
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    private void clearMarkers() {
        if (mAllCollegeMarker.size()>0) {
            for (Marker marker : mAllCollegeMarker) {
                marker.remove();
            }
            mAllCollegeMarker.clear();
        }

    }



    //获取需要换电车辆列表
    private void getUseCharging(LatLng latLng,boolean isRfresh) {
        if (isRfresh) {
            showLoadingDialog("正在刷新");
        }

        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.USER_CHANGING, networksJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null && !isFinishing()) {
                            if (chargetList != null) {
                                chargetList.clear();
                            }
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    int fifty = 0;
                                    int forty = 0;
                                    int thiry = 0;
                                    int twenty = 0;
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Charge charge = new Charge();
                                        charge.id = jsonArray.optJSONObject(i).optString("vehicle_id");
                                        charge.number = jsonArray.optJSONObject(i).optString("number");
                                        charge.city_path = jsonArray.optJSONObject(i).optString("city_path");
                                        charge.distance = jsonArray.optJSONObject(i).optString("distance");
                                        charge.battery = jsonArray.optJSONObject(i).optInt("battery");
                                        charge.status_name = jsonArray.optJSONObject(i).optString("status_name");
                                        charge.rssi = jsonArray.optJSONObject(i).optString("rssi");
                                        charge.glat = jsonArray.optJSONObject(i).optDouble("glat");
                                        charge.glng = jsonArray.optJSONObject(i).optDouble("glng");
                                        charge.voltage = jsonArray.optJSONObject(i).optString("voltage");

                                        if (charge.battery <= 50) {
                                            fifty = fifty + 1;
                                            chargetList.add(charge);
                                        }

                                        if (charge.battery <= 40) {
                                            forty = forty + 1;

                                        }
                                        if (charge.battery <= 30) {
                                            thiry = thiry + 1;

                                        }
                                        if (charge.battery <= 20) {
                                            twenty = twenty + 1;
                                        }
                                    }
                                    if (fifty > 0) {
                                        fiftyNumber.setText(fifty + "");
                                        fiftyNumber.setVisibility(View.VISIBLE);
                                    } else {
                                        fiftyNumber.setVisibility(View.INVISIBLE);
                                    }

                                    if (forty > 0) {
                                        fortyNumber.setText(forty + "");
                                        fortyNumber.setVisibility(View.VISIBLE);
                                    } else {
                                        fortyNumber.setVisibility(View.GONE);
                                    }

                                    if (thiry > 0) {
                                        thirtyNumber.setText(thiry + "");
                                        thirtyNumber.setVisibility(View.VISIBLE);
                                    } else {
                                        thirtyNumber.setVisibility(View.INVISIBLE);
                                    }

                                    if (twenty > 0) {
                                        twentyNumber.setText(twenty + "");
                                        twentyNumber.setVisibility(View.VISIBLE);
                                    } else {
                                        twentyNumber.setVisibility(View.INVISIBLE);
                                    }

                                    changeBatteryListAdapter.setNewData(chargetList);

                                    showMarkers(50);
                                    title.setText(getString(R.string.shortage_car_battary_txt) + "(" + chargetList.size() + ")");

                                } else {
                                    title.setText(getString(R.string.shortage_car_battary_txt));
                                    thirtyNumber.setVisibility(View.INVISIBLE);
                                    fortyNumber.setVisibility(View.INVISIBLE);
                                    fiftyNumber.setVisibility(View.INVISIBLE);
                                    twentyNumber.setVisibility(View.INVISIBLE);
                                }
                            } else {
                                dismissLoadingDialog();
                                title.setText(getString(R.string.shortage_car_battary_txt));
                                thirtyNumber.setVisibility(View.INVISIBLE);
                                fortyNumber.setVisibility(View.INVISIBLE);
                                fiftyNumber.setVisibility(View.INVISIBLE);
                                twentyNumber.setVisibility(View.INVISIBLE);
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (chargetList.size() <= 0) {
                        changeBatteryListAdapter.setEmptyView(LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.empty_view, null));
                    } else {
                        recyclerView.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 14));
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    //换完电池按完成
    private void batteryFinish(final String number) {
        showLoadingDialog("请稍候...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", "1");
        jsonObject.addProperty("type", "5");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                AlertDialog.Builder builder1 = new AlertDialog.Builder(ChangeBatteryActivity.this, R.style.RcDialog);
                                View view2 = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.later_battery, null);
                                final AlertDialog dialog1 = builder1.create();
                                dialog1.setView(view2);
                                dialog1.show();
                                TextView laterBatterysStatus = view2.findViewById(R.id.later_batterys_status);
                                TextView carNumber = view2.findViewById(R.id.car_number);
                                TextView laterBattery = view2.findViewById(R.id.later_battery);
                                TextView batteryRemarks = view2.findViewById(R.id.battery_remarks);
                                TextView yesDialogAsk = view2.findViewById(R.id.yes_dialog_ask);

                                int returnCodes = jsonObject.optJSONObject("data").optInt("return_code");

                                int afterBattery = jsonObject.optJSONObject("data").optInt("battery");

                                if (returnCodes == 1) {//判断returnCodes等于1时候表示更换电池成功
                                    laterBatterysStatus.setText("更换电池成功");
                                    batteryRemarks.setVisibility(View.GONE);
                                    getUseCharging(latLng,true);
                                    getStation(latLng);
                                } else {
                                    laterBatterysStatus.setText("更换电池失败!");
                                    batteryRemarks.setVisibility(View.VISIBLE);
                                }
                                StringBuilder carNumberBulider=new StringBuilder();
                                carNumberBulider.append("车辆编号:").append(number);
                                carNumber.setText(carNumberBulider.toString());

                                StringBuilder newBatteryBulider=new StringBuilder();
                                newBatteryBulider.append("最新电量:").append(afterBattery+"").append("%");
                                laterBattery.setText(newBatteryBulider.toString());

                                yesDialogAsk.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog1.dismiss();
                                    }
                                });
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }else if ("1002".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
               dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public void initData() {}


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 108) {
            String imel = data.getStringExtra("IMEI");
            if (!StringUtils.isEmpty(imel)) {
                getCarinfo(imel);
            }

        }
    }

    private void getCarinfo(String number) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.BOX_STATUS, jsonObject.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                String batterys=jsonObject.optJSONObject("data").optString("battery").replace("%","");
                                int currentBattery = StringUtils.toInt(batterys);
                                if (currentBattery<=50) {
                                    ToastUtil.showToast("车辆编号:"+jsonObject.optJSONObject("data").optString("number")+" 请更换电池");
                                }else {
                                    changBatteryDialog(jsonObject);
                                }

                            }  else if ("1001".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }else if ("1002".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast("获取车辆信息失败");

            }
        });
    }

    private void changBatteryDialog(JSONObject jsonObject) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ChangeBatteryActivity.this, R.style.activity_dialog);
        View view = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.changebattery_dialog, null);
        final AlertDialog changBatterydialog = builder.create();
        changBatterydialog.setView(view);
        changBatterydialog.show();
        final TextView numbers = view.findViewById(R.id.number);
        TextView address = view.findViewById(R.id.address);
        TextView batterys = view.findViewById(R.id.batterys);
        numbers.setText(jsonObject.optJSONObject("data").optString("number"));
        if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("city_path"))) {
            address.setText("未知地址");
        } else {
            address.setText(jsonObject.optJSONObject("data").optString("city_path"));
        }
        batterys.setText(jsonObject.optJSONObject("data").optString("battery"));
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(jsonObject.optJSONObject("data").optDouble("glat"), jsonObject.optJSONObject("data").optDouble("glng")), 15f));
        final Button startdenfense = view.findViewById(R.id.startdefense_btn);
        Button withdrawdevice = view.findViewById(R.id.withdrawdevice_btn);
        Button oppaccBtn = view.findViewById(R.id.oppacc_btn);
        Button playBtn = view.findViewById(R.id.play_btn);
        Button gpsBtn = view.findViewById(R.id.gps_btn);
        Button finish = view.findViewById(R.id.finish_btn);
        startdenfense.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//撤防
                sendCommand(numbers.getText().toString(), "0", "3", "5");
            }
        });
        withdrawdevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//设防
                sendCommand(numbers.getText().toString(), "1", "3", "6");
            }
        });
        oppaccBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCommand(numbers.getText().toString(), "0", "5", "3");
            }
        });

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCommand(numbers.getText().toString(), "0", "1", "4");
            }
        });
        gpsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCommand(numbers.getText().toString(), "0", "9", "");
            }
        });
        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                batteryFinish(numbers.getText().toString());
            }
        });
    }


    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(final Marker marker) {
            clickMaker = marker;
            marker.showInfoWindow();
            marker.setTitle("");
            return true;
        }
    };

    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            View view = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.battery_bubble, null);
            final TextView number = view.findViewById(R.id.number);
            TextView battery = view.findViewById(R.id.battery);
            TextView carstatus = view.findViewById(R.id.carstatus);//车辆状态
            TextView showrssi = view.findViewById(R.id.rssi);
            TextView carlocations = view.findViewById(R.id.carlocations);
            Button playbtn = view.findViewById(R.id.play_btn);
            Button startdefenseBtn = view.findViewById(R.id.startdefense_btn);
            Button oppaccBtn = view.findViewById(R.id.oppacc_btn);
            Button withdrawdeviceBtn = view.findViewById(R.id.withdrawdevice_btn);
            Button gpsBtn = view.findViewById(R.id.gps_btn);
            Button finishBtn = view.findViewById(R.id.finish_btn);
            Button nav = view.findViewById(R.id.nav_btn);
            final Charge info = (Charge) marker.getObject();

            StringBuilder carNumberString = new StringBuilder();
            carNumberString.append("车辆编号: ").append(info.number);
            number.setText(carNumberString.toString());

            StringBuilder batteryString = new StringBuilder();
            batteryString.append("电量: ").append(info.battery).append("%");
            battery.setText(batteryString.toString());

            StringBuilder carstatusString = new StringBuilder();
            carstatusString.append("车辆状态: ").append(info.status_name);
            carstatus.setText(carstatusString.toString());

            StringBuilder rssiString = new StringBuilder();
            rssiString.append("信号强度：").append(info.rssi);
            showrssi.setText(rssiString.toString());

            StringBuilder carAddressBulider = new StringBuilder();
            carAddressBulider.append("车辆地址：").append(info.city_path);
            if (!StringUtils.isEmpty(info.city_path)) {
                carlocations.setText(carAddressBulider.toString());
            } else {
                carlocations.setText("车辆地址：无");
            }

            startdefenseBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sendCommand(info.getNumber(), "1", "2", "1");
                }
            });
            withdrawdeviceBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sendCommand(info.getNumber(), "0", "2", "2");
                }
            });
            oppaccBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "5", "3");
                }
            });

            playbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sendCommand(info.getNumber(), "0", "1", "4");
                }
            });

            gpsBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCommand(info.getNumber(), "0", "9", "");
                }
            });

            finishBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    batteryFinish(info.getNumber());

                }
            });
            nav.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ChangeBatteryActivity.this, AMapNaviActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putDouble("currentLat", currentLatitude);
                    bundle.putDouble("currentLng", currentLongitude);
                    bundle.putDouble("targetLat", info.glat);
                    bundle.putDouble("targetLng", info.glng);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            return view;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    };

    //点击marker就消失
    AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    };


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            if (isFirstLoc) {
                currentLatitude = aMapLocation.getLatitude();
                currentLongitude = aMapLocation.getLongitude();
                latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                getStation(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                getUseCharging(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()),false);
                isFirstLoc = false;

            }
        }
    }

    /**
     * 统一下发指令,第一参数是车辆编号，第二个开关,第三个是什么类型指令，第四个是蓝牙命令类型
     * @param number 车辆编号
     * @param sw 开关：（电门：1开启，0关闭）（设防：1设防，0撤防）（电机锁：1上锁，0解锁）（电池锁：1完成，0开仓）；默认0
     * @param type 1寻车，2电门开关，3设防撤防，4电机锁，5电池锁，6刷新定位，7查看定位，8设备重启，9GPS信号重启
     * @param blueCommandType 蓝牙命令类型
     */
    private void sendCommand(final String number, final String sw, final String type, final String blueCommandType) {
        showLoadingDialog("正在下发命令...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", sw);
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_bluetooth", "0");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                if (jsonObject.optString("data").equals("{}")) {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else {
                                    //显示蓝牙连接的对话框
                                    showBlueTeethDialog(jsonObject, number, blueCommandType);

                                }
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
               dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void showBlueTeethDialog(final JSONObject jsonObject, final String number, final String blueCommandType) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ChangeBatteryActivity.this, R.style.activity_dialog);
        View view = LayoutInflater.from(ChangeBatteryActivity.this).inflate(R.layout.blue_endcar_dialog, null);
        final AlertDialog conituredialog = builder.create();
        conituredialog.setView(view);
        conituredialog.show();
        final TextView contents = view.findViewById(R.id.content);
        final Button endCarstartCars = view.findViewById(R.id.start_cars);
        final Button cancel = view.findViewById(R.id.cancel);
        contents.setText(jsonObject.optString("message"));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conituredialog.dismiss();
            }
        });
        endCarstartCars.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conituredialog.dismiss();
                if (!mBlueadapter.isEnabled()) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                } else {
                    connectBlueTeeth(number, jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"), blueCommandType);
                }

            }
        });
    }

    //蓝牙连接，第一个参数暂时无用，第二个设备编号，第三个密钥，第四个作为不同功能指令区分
    private void connectBlueTeeth(final String number, String devices, String token, final String blueCommandType) {
        showLoadingDialog("正在连接蓝牙中");
        TbitBle.connect(devices, token, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                if (resultCode == 0) {
                    if (blueCommandType.equals("1")) {//启动
                         unlockDevice(number);
                    } else if (blueCommandType.equals("2")) {//关闭
                        defenseBlueteethDevice(number,"1");
                    } else if (blueCommandType.equals("3")) {//开仓
                        openAccBlueteethDevice(number);
                    } else if (blueCommandType.equals("4")) {//播报
                        findCarBlueteethDevice(number);
                    }else if (blueCommandType.equals("5")) {//撤防
                        defenseCloseBlueteethDevice(number);
                    }else if (blueCommandType.equals("6")) {//设防
                        defenseBlueteethDevice(number,"2");

                    }
                } else {
                   dismissLoadingDialog();
                    ToastUtil.showToast( " 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {

            }
        });
    }

    private void openAccBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x05, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                        dismissLoadingDialog();
                        // 发送状态回复
                        if (resultCode == 0) {
                            sendCommandWithBlueTeeth(number,"0","5");
                        } else {
                            ToastUtil.showToast("蓝牙操作失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }

    //寻车蓝牙命令
    private void findCarBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x04, new Byte[]{0x01},
                new ResultCallback() {
                    @Override
                    public void onResult(int resultCode) {
                        dismissLoadingDialog();
                        // 发送状态回复
                        if (resultCode == 0) {
                            sendCommandWithBlueTeeth(number,"0","1");
                            Log.e("寻车蓝牙指令状态码-->", resultCode + "");
                        } else {
                            ToastUtil.showToast("蓝牙操作失败，请重新再试");
                        }
                    }
                }, new PacketCallback() {
                    @Override
                    public void onPacketReceived(Packet packet) {
                        // 收到packet回复
                    }
                });

    }


    // 解锁
    private void unlockDevice(final String number) {
        TbitBle.unlock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                // 解锁回应
                Log.e("解锁回应-->", resultCode + "");
                if (resultCode == 0) {
                    sendCommandWithBlueTeeth(number,"1","2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        });
    }

    // 上锁
    private void lockDevice() {
        TbitBle.lock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 上锁回应
                Log.e("上锁回应-->", resultCode + "");
            }
        });
    }

    //设防开启蓝牙命令
    private void defenseBlueteethDevice(final String number,final String type) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x01}, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 发送状态回复
                dismissLoadingDialog();
                if (resultCode == 0) {
                    if (type.equals("1")) {
                        sendCommandWithBlueTeeth(number,"0","2");
                    }else {
                        sendCommandWithBlueTeeth(number,"1","3");
                    }
                } else {
                    ToastUtil.showToast( "蓝牙操作失败，请重新再试");
                }
            }
        }, new PacketCallback() {
            @Override
            public void onPacketReceived(Packet packet) {
                // 收到packet回复
            }
        });

    }


    //撤防蓝牙命令
    private void defenseCloseBlueteethDevice(final String number) {
        TbitBle.commonCommand((byte) 0x03, (byte) 0x01, new Byte[]{0x00}, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                // 发送状态回复
                if (resultCode == 0) {
                    sendCommandWithBlueTeeth(number,"0","3");
                } else {
                    ToastUtil.showToast( " 蓝牙连接失败，请重新再试");
                }
            }
        }, new PacketCallback() {
            @Override
            public void onPacketReceived(Packet packet) {
                // 收到packet回复
            }
        });

    }


    private void sendCommandWithBlueTeeth(String number, String sw, String type) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", sw);
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("is_bluetooth", "1");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result)throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                               dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }

                }
            }

            @Override
            public void failedRequest(String result) {
               dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //小安设备蓝牙连接
    public void connectBlueTeeth(final String number, String imei, final String xaCommandType) {
        showLoadingDialog("正在连接蓝牙中...");
        if (null != apiClient) {
            apiClient.connectToIMEI(imei);
        }
        builder.setBleStateChangeListener(new BleStateChangeListener() {
            @Override
            public void onConnect(BluetoothDevice bluetoothDevice) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (xaCommandType.equals("1")) {//启动
                            setAcc(number);
                        }else  if (xaCommandType.equals("2")) {//关闭
                            setundefend(number);
                        }else  if (xaCommandType.equals("3")) {//开仓
                            setsaddle(number);
                        }else  if (xaCommandType.equals("4")) {//播放
                            findcar(number);

                        }

                    }
                });
            }

            @Override
            public void onDisConnect(BluetoothDevice bluetoothDevice) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtil.showToast("蓝牙连接失败,请重新连接 ");
                    }
                });
            }

            @Override
            public void onDeviceReady(BluetoothDevice bluetoothDevice) {}

            @Override
            public void onReadRemoteRssi(int i) {}

            @Override
            public void onError(BluetoothDevice bluetoothDevice, String s, int i) {

            }

            @Override
            public void onBleAdapterStateChanged(int i) {}
        });
    }


    public void shutdown() {//关闭
        apiClient.shutdown(new BleCallback() {
            @Override
            public void onResponse(Response response) {
                Log.e("shutdown", response.toString());
            }
        });
    }

    //寻车
    public void findcar(final String number) {
        apiClient.findCar(new BleCallback() {
            @Override
            public void onResponse(Response response) {
                Log.e("寻车", response.toString());
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "1");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请重新再试");
                }
            }
        });
    }

    //撤防
    public void setundefend(final String number) {
        apiClient.setDefend(false, new BleCallback() {
            @Override
            public void onResponse(final Response response) {
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请重新再试");
                }
            }
        });
    }

    //电池仓开
    public void setsaddle(final String number) {
        apiClient.setSaddle(true, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "0", "5");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请重新再试");
                }
            }
        });
    }


    public void setAcc(final String number) {
        apiClient.setAcc(true, new BleCallback() {
            @Override
            public void onResponse(Response response) {
                dismissLoadingDialog();
                if (response.code==0) {
                    sendCommandWithBlueTeeth(number, "1", "2");
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请重新再试");
                }
            }
        });
    }


}
